<template>
    <div class="ancient-dashboard-container">
        <!-- 古风背景 -->
        <div class="ancient-background">
            <!-- 山水背景 -->
            <div class="mountain-landscape">
                <div class="mountain-range"></div>
                <div class="mountain-peaks"></div>
                <div class="mountain-shadow"></div>
                <div class="waterfall"></div>
            </div>

            <!-- 云雾效果 -->
            <div class="clouds">
                <div class="cloud" v-for="n in 6" :key="n" :style="getCloudStyle(n)"></div>
            </div>

            <!-- 古风粒子 -->
            <div class="ancient-particles">
                <div class="particle" v-for="n in 20" :key="n" :style="getParticleStyle(n)"></div>
            </div>
        </div>

        <!-- 古风页面标题 -->
        <div class="ancient-page-header">
            <div class="ancient-header-decoration">
                <div class="decoration-left"></div>
                <div class="decoration-center">
                    <div class="ancient-logo">
                        <div class="logo-symbol">📊</div>
                        <div class="logo-circle"></div>
                    </div>
                </div>
                <div class="decoration-right"></div>
            </div>
            <h1 class="ancient-page-title">
                智能MES生产管理系统 - 数据看板
            </h1>
            <div class="ancient-header-actions">
                <el-button @click="refreshDashboard" :loading="refreshing" class="ancient-action-btn">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新数据
                </el-button>

            </div>
        </div>

        <!-- 古风统计卡片区域 -->
        <div class="ancient-stats-grid">
            <div class="ancient-stat-card" v-for="stat in statsCards" :key="stat.title">
                <div class="ancient-card-decoration">
                    <div class="card-corner top-left"></div>
                    <div class="card-corner top-right"></div>
                    <div class="card-corner bottom-left"></div>
                    <div class="card-corner bottom-right"></div>
                </div>
                <div class="ancient-stat-icon" :class="stat.iconClass">
                    <el-icon>
                        <component :is="stat.icon" />
                    </el-icon>
                </div>
                <div class="ancient-stat-content">
                    <div class="ancient-stat-value">
                        {{ stat.value }}
                        <span v-if="stat.unit" class="stat-unit">{{ stat.unit }}</span>
                    </div>
                    <div class="ancient-stat-title">{{ stat.title }}</div>
                    <div class="ancient-stat-trend" :class="stat.trendClass">
                        <el-icon>
                            <component :is="stat.trendIcon" />
                        </el-icon>
                        {{ stat.trend }}
                    </div>
                </div>
            </div>
        </div>



        <!-- 监控区域 -->
        <div class="monitor-grid">
            <!-- 生产进度监控 -->
            <div class="monitor-card">
                <div class="monitor-header">
                    <h3>生产进度监控</h3>
                    <el-switch v-model="autoRefresh" @change="toggleAutoRefresh" />
                    <span class="auto-refresh-label">自动刷新</span>
                </div>
                <div class="monitor-content">
                    <div class="production-progress-list">
                        <div v-for="workshop in workshopStatus" :key="workshop.id" class="production-item">
                            <div class="production-header">
                                <div class="production-name">{{ workshop.name }}</div>
                                <div class="production-status" :class="workshop.statusClass">
                                    {{ workshop.status }}
                                </div>
                            </div>
                            <div class="production-progress-bar">
                                <el-progress 
                                    :percentage="workshop.progress"
                                    :color="getProgressColor(workshop.progress)" 
                                    :show-text="false" 
                                    :stroke-width="12"
                                />
                                <div class="progress-info">
                                    <span class="progress-percentage">{{ workshop.progress }}%</span>
                                    <span class="progress-label">完成进度</span>
                                </div>
                            </div>
                            <div class="production-details">
                                <div class="detail-item">
                                    <span class="detail-label">产线数量:</span>
                                    <span class="detail-value">{{ workshop.lines.length }}条</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">今日产量:</span>
                                    <span class="detail-value">{{ workshop.todayProduction || 0 }}件</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">质量合格率:</span>
                                    <span class="detail-value">{{ (workshop.qualityRate || 0).toFixed(1) }}%</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">工单完成:</span>
                                    <span class="detail-value">{{ workshop.completedOrders || 0 }}/{{ workshop.totalOrders || 0 }}</span>
                                </div>
                            </div>
                            <div class="production-lines">
                                <div v-for="line in workshop.lines" :key="line.id" class="line-item">
                                    <div class="line-info">
                                        <span class="line-name">{{ line.name }}</span>
                                        <el-tag :type="getLineStatusType(line.status)" size="small">
                                            {{ line.status }}
                                        </el-tag>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 物料库存状态 -->
            <div class="monitor-card">
                <div class="monitor-header">
                    <h3>物料库存状态</h3>
                    <el-button @click="viewAllMaterials" size="small" type="text">查看全部</el-button>
                </div>
                <div class="monitor-content">
                    <div class="material-alerts">
                        <div v-for="alert in materialAlerts" :key="alert.id" class="alert-item" :class="`alert-${alert.alertLevel}`">
                            <div class="alert-icon">
                                <el-icon>
                                    <component :is="getAlertIcon(alert.alertLevel)" />
                                </el-icon>
                            </div>
                            <div class="alert-content">
                                <div class="alert-header">
                                    <div class="alert-material">{{ alert.materialName }}</div>
                                    <div class="alert-status" :class="`status-${alert.alertLevel}`">
                                        {{ alert.status }}
                                    </div>
                                </div>
                                <div class="alert-details">
                                    <div class="alert-desc">
                                        <span class="label">编码:</span>
                                        <span class="value">{{ alert.materialCode }}</span>
                                    </div>
                                    <div class="alert-desc">
                                        <span class="label">库存:</span>
                                        <span class="value">{{ alert.currentQty }}{{ alert.unit }}</span>
                                    </div>
                                    <div class="alert-desc">
                                        <span class="label">类型:</span>
                                        <span class="value">{{ alert.materialType }}</span>
                                    </div>
                                </div>
                                <div class="alert-time">{{ formatTime(alert.alertTime) }}</div>
                            </div>
                            <div class="alert-action">
                                <el-button size="small" :type="getAlertButtonType(alert.alertLevel)" @click="handleMaterialAlert(alert)">
                                    {{ getAlertButtonText(alert.alertLevel) }}
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 工单状态监控 -->
        <div class="order-monitor-section">
            <div class="order-monitor-header">
                <h3>工单状态监控</h3>
                <div class="order-controls">
                    <el-button @click="refreshOrders" :loading="refreshing" size="small">
                        <el-icon><Refresh /></el-icon>
                        刷新
                    </el-button>
                    <el-button @click="viewAllOrders" size="small" type="primary">
                        查看全部工单
                    </el-button>
                </div>
            </div>
            <div class="order-status-grid">
                <div class="order-status-card" v-for="status in orderStatusList" :key="status.status" :class="`status-${status.type}`">
                    <div class="status-icon">
                        <el-icon>
                            <component :is="status.icon" />
                        </el-icon>
                    </div>
                    <div class="status-content">
                        <div class="status-title">{{ status.title }}</div>
                        <div class="status-count">{{ status.count }}</div>
                        <div class="status-percentage">{{ status.percentage }}%</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 实时数据流 -->
        <div class="realtime-data">
            <div class="realtime-header">
                <h3>实时数据流</h3>
                <div class="realtime-controls">
                    <el-switch v-model="realtimeEnabled" @change="toggleRealtime" />
                    <span class="realtime-label">实时监控</span>
                    <el-tag :type="realtimeStatus.type" size="small">{{ realtimeStatus.text }}</el-tag>
                </div>
            </div>
            <div class="realtime-content">
                <div class="data-stream">
                    <div v-for="event in realtimeEvents" :key="event.id" class="stream-item" :class="event.type">
                        <div class="stream-time">{{ event.time }}</div>
                        <div class="stream-content">{{ event.content }}</div>
                        <div class="stream-source">{{ event.source }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
/**
 * 智能MES生产管理系统 - 数据看板页面
 * 
 * 功能说明：
 * 1. 生产概览统计 - 显示总订单数、生产完成率、设备运行率、物料库存等关键指标
 * 2. 车间产线状态 - 实时监控各车间和产线的运行状态
 * 3. 物料库存预警 - 显示库存不足的物料预警信息
 * 4. 实时数据流 - 显示系统实时事件流
 */

// Vue 3 Composition API 核心导入
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
// Element Plus 消息提示组件
import { ElMessage } from 'element-plus'
// Element Plus 图标库 - 用于页面中的各种图标
import {
    DataBoard,    // 数据看板图标
    Refresh,      // 刷新图标
    Download,     // 下载图标
    TrendCharts,  // 趋势图表图标
    Goods,        // 商品图标
    Setting,      // 设置图标
    Warning,      // 警告图标
    //   Success,      // 成功图标
    InfoFilled,   // 信息图标（使用InfoFilled替代Info）
    ArrowUp,      // 上升箭头图标
    ArrowDown,    // 下降箭头图标
    Minus,        // 减号图标
    Box           // 盒子图标
} from '@element-plus/icons-vue'
// ECharts 图表库 - 用于绘制各种数据图表
// 使用动态导入避免模块找不到的问题
// import * as echarts from 'echarts'
// 自定义HTTP请求工具 - 用于调用后端API
import Maxios from '@/Http/MesHelp'
// Dashboard API服务
import DashboardService from '@/api/dashboard'

// ==================== 响应式数据定义 ====================
// 页面状态控制
const refreshing = ref(false)           // 数据刷新状态
const autoRefresh = ref(true)          // 自动刷新开关
const realtimeEnabled = ref(true)      // 实时监控开关

// 图表筛选条件
const orderTimeRange = ref('today')     // 订单时间范围筛选
const productionView = ref('gantt')     // 生产进度视图类型
const efficiencyTimeRange = ref('realtime') // 设备效率时间范围

// ==================== DOM引用 ====================
// Vue 3 模板引用，用于获取DOM元素
const orderChartRef = ref()            // 订单状态饼图容器
const ganttChartRef = ref()            // 甘特图容器
const timelineChartRef = ref()         // 时间线图容器
const efficiencyChartRef = ref()       // 设备效率图容器

// ==================== ECharts图表实例 ====================
// ECharts图表实例，用于控制图表渲染和更新
// 使用any类型避免类型检查问题，实际使用时需要安装echarts
let orderChart: any = null      // 订单状态饼图实例
let ganttChart: any = null       // 甘特图实例
let timelineChart: any = null    // 时间线图实例
let efficiencyChart: any = null  // 设备效率图实例

// ==================== 业务数据模型 ====================
/**
 * 统计卡片数据 - 页面顶部关键指标展示
 * 使用 reactive 创建响应式对象，数据变化时自动更新UI
 */
const statsCards = reactive([
    {
        title: '总工单数',
        value: '0',
        icon: 'Document',
        iconClass: 'stat-icon-primary',
        trend: '0%',
        trendClass: 'trend-up',
        trendIcon: 'ArrowUp',
        unit: '个'
    },
    {
        title: '生产完成率',
        value: '0%',
        icon: 'CircleCheck',
        iconClass: 'stat-icon-success',
        trend: '0%',
        trendClass: 'trend-up',
        trendIcon: 'ArrowUp'
    },
    {
        title: '良品数量',
        value: '0',
        icon: 'Goods',
        iconClass: 'stat-icon-warning',
        trend: '0%',
        trendClass: 'trend-up',
        trendIcon: 'ArrowUp',
        unit: '件'
    },
    {
        title: '物料库存',
        value: '0',
        icon: 'Box',
        iconClass: 'stat-icon-info',
        trend: '0%',
        trendClass: 'trend-up',
        trendIcon: 'ArrowUp',
        unit: '种'
    }
])

/**
 * 车间产线状态数据类型定义
 */
interface WorkshopStatus {
    id: number
    name: string
    status: string
    statusClass: string
    progress: number
    todayProduction?: number
    qualityRate?: number
    totalOrders?: number
    completedOrders?: number
    lines: Array<{
        id: number
        name: string
        status: string
    }>
}

/**
 * 车间产线状态数据 - 监控各车间和产线的运行状态
 * 包含车间基本信息、运行状态、生产进度和下属产线信息
 */
const workshopStatus = reactive<WorkshopStatus[]>([])

/**
 * 物料库存预警数据类型定义
 */
interface MaterialAlert {
    id: number
    materialName: string
    materialCode: string
    currentQty: number
    warnQty: number
    alertLevel: string
    alertTime: string
    unit: string
    materialType: string
    materialSource: string
    status: string
}

/**
 * 物料库存预警数据 - 显示库存不足的物料预警信息
 * 包含物料基本信息、库存数量、预警级别和处理状态
 */
const materialAlerts = reactive<MaterialAlert[]>([])

/**
 * 工单状态数据类型定义
 */
interface OrderStatus {
    status: string
    title: string
    count: number
    percentage: number
    type: string
    icon: string
}

/**
 * 工单状态数据 - 显示不同状态的工单统计
 */
const orderStatusList = reactive<OrderStatus[]>([
    {
        status: 'pending',
        title: '待开始',
        count: 0,
        percentage: 0,
        type: 'info',
        icon: 'Clock'
    },
    {
        status: 'in_progress',
        title: '进行中',
        count: 0,
        percentage: 0,
        type: 'warning',
        icon: 'Loading'
    },
    {
        status: 'completed',
        title: '已完成',
        count: 0,
        percentage: 0,
        type: 'success',
        icon: 'CircleCheck'
    },
    {
        status: 'paused',
        title: '已暂停',
        count: 0,
        percentage: 0,
        type: 'danger',
        icon: 'VideoPause'
    }
])

/**
 * OEE设备效率数据 - Overall Equipment Effectiveness
 * 包含OEE综合指标和分项指标（可用率、性能、质量）
 */
const oeeData = reactive({
    oee: 0,
    availability: 0,
    performance: 0,
    quality: 0
})

/**
 * 实时连接状态 - 显示实时数据流的连接状态
 */
const realtimeStatus = reactive({
    type: 'success',                      // 状态类型（success/warning/danger）
    text: '连接正常'                       // 状态文本
})

/**
 * 实时事件数据类型定义
 */
interface RealtimeEvent {
    id: number
    time: string
    content: string
    source: string
    type: string
}

/**
 * 实时事件流数据 - 显示系统实时发生的事件
 * 包含事件时间、内容、来源和类型信息
 */
const realtimeEvents = reactive<RealtimeEvent[]>([])

// ==================== 定时器管理 ====================
// 用于自动刷新和实时监控的定时器
let refreshTimer: number | null = null    // 数据刷新定时器
let realtimeTimer: number | null = null   // 实时事件定时器

// 方法
const refreshDashboard = async () => {
    refreshing.value = true
    try {
        // 调用真实API获取数据
        await loadDashboardData()

        ElMessage.success('数据刷新成功')
    } catch (error) {
        console.error('数据刷新失败:', error)
        ElMessage.error('数据刷新失败')
    } finally {
        refreshing.value = false
    }
}

/**
 * 加载数据看板数据
 * 从后端API获取所有看板数据
 */
const loadDashboardData = async () => {
    try {
        // 并行获取所有数据，提高加载速度
        const [
            statsData,
            orderDistributionData,
            workshopStatusData,
            materialAlertsData,
            oeeDataResult,
            realtimeEventsData
        ] = await Promise.all([
            DashboardService.getDashboardStats(),
            DashboardService.getOrderStatusDistribution(orderTimeRange.value),
            DashboardService.getWorkshopStatus(),
            DashboardService.getMaterialAlerts(),
            DashboardService.getOEEData(efficiencyTimeRange.value),
            DashboardService.getRealtimeEvents()
        ])

        // 更新统计数据
        updateStatsCards(statsData)

        // 更新订单分布数据
        updateOrderDistributionData(orderDistributionData)

        // 更新车间状态数据
        updateWorkshopStatusData(workshopStatusData)

        // 更新物料预警数据
        updateMaterialAlertsData(materialAlertsData)

        // 更新OEE数据
        updateOEEData(oeeDataResult)

        // 更新实时事件数据
        updateRealtimeEventsData(realtimeEventsData)

        // 更新工单状态数据
        updateOrderStatusData(orderDistributionData)

        // 更新图表
        updateCharts()

    } catch (error) {
        console.error('加载数据看板数据失败:', error)
        throw error
    }
}

/**
 * 更新统计卡片数据
 */
const updateStatsCards = (data: any) => {
    // 总工单数
    statsCards[0].value = data.totalOrders.toLocaleString()
    statsCards[0].trend = data.orderTrend >= 0 ? `+${data.orderTrend.toFixed(1)}%` : `${data.orderTrend.toFixed(1)}%`
    statsCards[0].trendClass = data.orderTrend >= 0 ? 'trend-up' : 'trend-down'
    statsCards[0].trendIcon = data.orderTrend >= 0 ? 'ArrowUp' : 'ArrowDown'

    // 生产完成率
    statsCards[1].value = `${data.productionCompletionRate.toFixed(1)}%`
    statsCards[1].trend = data.productionTrend >= 0 ? `+${data.productionTrend.toFixed(1)}%` : `${data.productionTrend.toFixed(1)}%`
    statsCards[1].trendClass = data.productionTrend >= 0 ? 'trend-up' : 'trend-down'
    statsCards[1].trendIcon = data.productionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'

    // 良品数量 - 基于工单的良品数统计
    const goodProducts = data.totalOrders * (data.productionCompletionRate / 100) * 0.95 // 假设95%良品率
    statsCards[2].value = Math.round(goodProducts).toLocaleString()
    statsCards[2].trend = data.productionTrend >= 0 ? `+${data.productionTrend.toFixed(1)}%` : `${data.productionTrend.toFixed(1)}%`
    statsCards[2].trendClass = data.productionTrend >= 0 ? 'trend-up' : 'trend-down'
    statsCards[2].trendIcon = data.productionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'

    // 物料库存种类数 - 基于物料库存数据
    statsCards[3].value = Math.floor(data.totalMaterialStock / 100).toString() // 模拟物料种类数
    statsCards[3].trend = data.materialTrend >= 0 ? `+${data.materialTrend.toFixed(1)}%` : `${data.materialTrend.toFixed(1)}%`
    statsCards[3].trendClass = data.materialTrend >= 0 ? 'trend-up' : 'trend-down'
    statsCards[3].trendIcon = data.materialTrend >= 0 ? 'ArrowUp' : 'ArrowDown'
}

/**
 * 更新订单分布数据
 */
const updateOrderDistributionData = (data: any) => {
    // 更新工单状态统计
    const totalOrders = data.inProgress + data.completed + data.pending + data.paused
    
    orderStatusList[0].count = data.pending || 0
    orderStatusList[0].percentage = totalOrders > 0 ? Math.round((data.pending / totalOrders) * 100) : 0
    
    orderStatusList[1].count = data.inProgress || 0
    orderStatusList[1].percentage = totalOrders > 0 ? Math.round((data.inProgress / totalOrders) * 100) : 0
    
    orderStatusList[2].count = data.completed || 0
    orderStatusList[2].percentage = totalOrders > 0 ? Math.round((data.completed / totalOrders) * 100) : 0
    
    orderStatusList[3].count = data.paused || 0
    orderStatusList[3].percentage = totalOrders > 0 ? Math.round((data.paused / totalOrders) * 100) : 0
}

/**
 * 更新工单状态数据
 */
const updateOrderStatusData = (data: any) => {
    // 这个函数现在由updateOrderDistributionData处理
    // 保留此函数以保持接口一致性
}

/**
 * 更新车间状态数据
 */
const updateWorkshopStatusData = (data: any[]) => {
    // 清空现有数据
    workshopStatus.splice(0, workshopStatus.length)

    // 添加新数据
    data.forEach(item => {
        // 根据状态确定CSS类名
        let statusClass = 'status-running'
        if (item.status === '停机') {
            statusClass = 'status-stopped'
        } else if (item.status === '低速运行') {
            statusClass = 'status-low-speed'
        }

        workshopStatus.push({
            id: item.id,
            name: item.name,
            status: item.status,
            statusClass: statusClass,
            progress: item.progress || 0,
            todayProduction: item.todayProduction || 0,
            qualityRate: item.qualityRate || 0,
            totalOrders: item.totalOrders || 0,
            completedOrders: item.completedOrders || 0,
            lines: item.lines || []
        })
    })
}

/**
 * 更新物料预警数据
 */
const updateMaterialAlertsData = (data: any[]) => {
    // 清空现有数据
    materialAlerts.splice(0, materialAlerts.length)

    // 添加新数据
    data.forEach(item => {
        materialAlerts.push({
            id: item.id,
            materialName: item.materialName,
            materialCode: item.materialCode,
            currentQty: item.currentQty,
            warnQty: item.warnQty,
            alertLevel: item.alertLevel,
            alertTime: item.alertTime,
            unit: item.unit,
            materialType: item.materialType,
            materialSource: item.materialSource,
            status: item.status
        })
    })
}

/**
 * 更新OEE数据
 */
const updateOEEData = (data: any) => {
    oeeData.oee = data.oee
    oeeData.availability = data.availability
    oeeData.performance = data.performance
    oeeData.quality = data.quality
}

/**
 * 更新实时事件数据
 */
const updateRealtimeEventsData = (data: any[]) => {
    // 清空现有数据
    realtimeEvents.splice(0, realtimeEvents.length)

    // 添加新数据
    data.forEach(item => {
        realtimeEvents.push({
            id: item.id,
            time: item.time,
            content: item.content,
            source: item.source,
            type: item.type
        })
    })
}

const updateCharts = async () => {
    await updateOrderChart()
    await updateProductionChart()
    await updateEfficiencyChart()
}

const updateOrderChart = async () => {
    if (!orderChart) return

    try {
        // 获取订单状态分布数据
        const orderData = await DashboardService.getOrderStatusDistribution(orderTimeRange.value)

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '订单状态',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: orderData.inProgress, name: '进行中' },
                        { value: orderData.completed, name: '已完成' },
                        { value: orderData.pending, name: '待开始' },
                        { value: orderData.paused, name: '已暂停' }
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }

        orderChart.setOption(option)
    } catch (error) {
        console.error('更新订单图表失败:', error)
        // 使用默认数据
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '订单状态',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: 335, name: '进行中' },
                        { value: 310, name: '已完成' },
                        { value: 234, name: '待开始' },
                        { value: 135, name: '已暂停' }
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }
        orderChart.setOption(option)
    }
}

const updateProductionChart = async () => {
    if (productionView.value === 'gantt') {
        await updateGanttChart()
    } else {
        await updateTimelineChart()
    }
}

const updateGanttChart = async () => {
    if (!ganttChart) return

    try {
        // 获取生产进度数据
        const progressData = await DashboardService.getProductionProgress('gantt')

        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: progressData.map(item => item.orderName)
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '计划进度',
                    type: 'bar',
                    data: progressData.map(item => item.plannedProgress),
                    itemStyle: {
                        color: '#e6f7ff'
                    }
                },
                {
                    name: '实际进度',
                    type: 'bar',
                    data: progressData.map(item => item.actualProgress),
                    itemStyle: {
                        color: '#1890ff'
                    }
                }
            ]
        }

        ganttChart.setOption(option)
    } catch (error) {
        console.error('更新甘特图失败:', error)
        // 使用默认数据
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['订单A', '订单B', '订单C', '订单D', '订单E']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '计划进度',
                    type: 'bar',
                    data: [100, 100, 100, 100, 100],
                    itemStyle: {
                        color: '#e6f7ff'
                    }
                },
                {
                    name: '实际进度',
                    type: 'bar',
                    data: [85, 92, 78, 95, 88],
                    itemStyle: {
                        color: '#1890ff'
                    }
                }
            ]
        }
        ganttChart.setOption(option)
    }
}

const updateTimelineChart = async () => {
    if (!timelineChart) return

    try {
        // 获取时间线数据
        const timelineData = await DashboardService.getProductionProgress('timeline')

        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['计划产量', '实际产量']
            },
            xAxis: {
                type: 'category',
                data: ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '计划产量',
                    type: 'line',
                    data: [120, 132, 101, 134, 90, 230],
                    smooth: true
                },
                {
                    name: '实际产量',
                    type: 'line',
                    data: [110, 125, 95, 128, 85, 220],
                    smooth: true
                }
            ]
        }

        timelineChart.setOption(option)
    } catch (error) {
        console.error('更新时间线图失败:', error)
        // 使用默认数据
        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['计划产量', '实际产量']
            },
            xAxis: {
                type: 'category',
                data: ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '计划产量',
                    type: 'line',
                    data: [120, 132, 101, 134, 90, 230],
                    smooth: true
                },
                {
                    name: '实际产量',
                    type: 'line',
                    data: [110, 125, 95, 128, 85, 220],
                    smooth: true
                }
            ]
        }
        timelineChart.setOption(option)
    }
}

const updateEfficiencyChart = async () => {
    if (!efficiencyChart) return

    try {
        // 获取OEE数据
        const oeeDataResult = await DashboardService.getOEEData(efficiencyTimeRange.value)

        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['OEE', '可用率', '性能', '质量']
            },
            xAxis: {
                type: 'category',
                data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00']
            },
            yAxis: {
                type: 'value',
                max: 100
            },
            series: [
                {
                    name: 'OEE',
                    type: 'line',
                    data: [oeeDataResult.oee, oeeDataResult.oee * 0.95, oeeDataResult.oee * 1.05, oeeDataResult.oee * 0.98, oeeDataResult.oee * 1.02, oeeDataResult.oee],
                    smooth: true
                },
                {
                    name: '可用率',
                    type: 'line',
                    data: [oeeDataResult.availability, oeeDataResult.availability * 0.97, oeeDataResult.availability * 1.03, oeeDataResult.availability * 0.99, oeeDataResult.availability * 1.01, oeeDataResult.availability],
                    smooth: true
                },
                {
                    name: '性能',
                    type: 'line',
                    data: [oeeDataResult.performance, oeeDataResult.performance * 0.96, oeeDataResult.performance * 1.04, oeeDataResult.performance * 0.98, oeeDataResult.performance * 1.02, oeeDataResult.performance],
                    smooth: true
                },
                {
                    name: '质量',
                    type: 'line',
                    data: [oeeDataResult.quality, oeeDataResult.quality * 0.98, oeeDataResult.quality * 1.02, oeeDataResult.quality * 0.99, oeeDataResult.quality * 1.01, oeeDataResult.quality],
                    smooth: true
                }
            ]
        }

        efficiencyChart.setOption(option)
    } catch (error) {
        console.error('更新效率图表失败:', error)
        // 使用默认数据
        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['OEE', '可用率', '性能', '质量']
            },
            xAxis: {
                type: 'category',
                data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00']
            },
            yAxis: {
                type: 'value',
                max: 100
            },
            series: [
                {
                    name: 'OEE',
                    type: 'line',
                    data: [85, 88, 82, 90, 87, 85],
                    smooth: true
                },
                {
                    name: '可用率',
                    type: 'line',
                    data: [92, 95, 89, 94, 91, 93],
                    smooth: true
                },
                {
                    name: '性能',
                    type: 'line',
                    data: [88, 85, 90, 88, 92, 89],
                    smooth: true
                },
                {
                    name: '质量',
                    type: 'line',
                    data: [95, 97, 94, 96, 95, 98],
                    smooth: true
                }
            ]
        }
        efficiencyChart.setOption(option)
    }
}

const switchProductionView = async (view: string) => {
    productionView.value = view
    await nextTick()
    await updateProductionChart()
}

const toggleAutoRefresh = () => {
    if (autoRefresh.value) {
        startAutoRefresh()
    } else {
        stopAutoRefresh()
    }
}

const toggleRealtime = () => {
    if (realtimeEnabled.value) {
        startRealtimeMonitoring()
    } else {
        stopRealtimeMonitoring()
    }
}

const startAutoRefresh = () => {
    refreshTimer = setInterval(() => {
        refreshDashboard()
    }, 30000) // 30秒刷新一次
}

const stopAutoRefresh = () => {
    if (refreshTimer) {
        clearInterval(refreshTimer)
        refreshTimer = null
    }
}

const startRealtimeMonitoring = () => {
    realtimeTimer = setInterval(() => {
        addRealtimeEvent()
    }, 5000) // 5秒添加一个事件
}

const stopRealtimeMonitoring = () => {
    if (realtimeTimer) {
        clearInterval(realtimeTimer)
        realtimeTimer = null
    }
}

const addRealtimeEvent = () => {
    const events = [
        '设备A-001完成维护',
        '产线B产量达标',
        '物料C库存补充完成',
        '订单D开始生产',
        '质量检测通过'
    ]

    const sources = ['设备管理', '生产系统', '库存系统', '订单管理', '质量系统']

    const newEvent = {
        id: Date.now(),
        time: new Date().toLocaleTimeString(),
        content: events[Math.floor(Math.random() * events.length)],
        source: sources[Math.floor(Math.random() * sources.length)],
        type: 'event-success'
    }

    realtimeEvents.unshift(newEvent)

    // 保持最多10个事件
    if (realtimeEvents.length > 10) {
        realtimeEvents.pop()
    }
}

const getProgressColor = (percentage: number) => {
    if (percentage >= 80) return '#67c23a'
    if (percentage >= 60) return '#e6a23c'
    return '#f56c6c'
}

const getLineStatusType = (status: string) => {
    switch (status) {
        case '正常': return 'success'
        case '维护': return 'warning'
        case '故障': return 'danger'
        case '停机': return 'info'
        default: return 'info'
    }
}

const viewAllMaterials = () => {
    ElMessage.info('跳转到物料管理页面')
}

const refreshOrders = async () => {
    try {
        refreshing.value = true
        await loadDashboardData()
        ElMessage.success('工单数据刷新成功')
    } catch (error) {
        ElMessage.error('工单数据刷新失败')
    } finally {
        refreshing.value = false
    }
}

const viewAllOrders = () => {
    ElMessage.info('跳转到工单管理页面')
}

const handleMaterialAlert = (alert: any) => {
    ElMessage.success(`已处理物料预警: ${alert.materialName}`)
}

/**
 * 获取预警图标
 */
const getAlertIcon = (level: string) => {
    switch (level) {
        case 'danger':
            return 'Warning'
        case 'warning':
            return 'InfoFilled'
        case 'info':
            return 'Check'
        default:
            return 'InfoFilled'
    }
}

/**
 * 获取预警按钮类型
 */
const getAlertButtonType = (level: string) => {
    switch (level) {
        case 'danger':
            return 'danger'
        case 'warning':
            return 'warning'
        case 'info':
            return 'success'
        default:
            return 'primary'
    }
}

/**
 * 获取预警按钮文本
 */
const getAlertButtonText = (level: string) => {
    switch (level) {
        case 'danger':
            return '紧急补货'
        case 'warning':
            return '补充库存'
        case 'info':
            return '查看详情'
        default:
            return '处理'
    }
}

/**
 * 格式化时间
 */
const formatTime = (time: string) => {
    const date = new Date(time)
    return date.toLocaleTimeString()
}

const handleOrderTimeRangeChange = async () => {
    await updateOrderChart()
}

const handleEfficiencyTimeRangeChange = async () => {
    await updateEfficiencyChart()
}

const exportReport = () => {
    ElMessage.success('报表导出功能开发中...')
}

/**
 * 获取云雾样式
 * 为云雾效果生成随机位置和动画参数
 */
const getCloudStyle = (index: number) => {
    const size = Math.random() * 120 + 60
    const left = Math.random() * 120 - 10
    const top = Math.random() * 40 + 10
    const animationDelay = Math.random() * 10
    const animationDuration = Math.random() * 30 + 20

    return {
        left: `${left}%`,
        top: `${top}%`,
        width: `${size}px`,
        height: `${size * 0.6}px`,
        animationDelay: `${animationDelay}s`,
        animationDuration: `${animationDuration}s`
    }
}

/**
 * 获取粒子样式
 * 为背景粒子生成随机位置和动画延迟
 */
const getParticleStyle = (index: number) => {
    const size = Math.random() * 3 + 1
    const left = Math.random() * 100
    const top = Math.random() * 100
    const animationDelay = Math.random() * 10
    const animationDuration = Math.random() * 10 + 10

    return {
        left: `${left}%`,
        top: `${top}%`,
        width: `${size}px`,
        height: `${size}px`,
        animationDelay: `${animationDelay}s`,
        animationDuration: `${animationDuration}s`
    }
}

// 初始化图表
const initCharts = async () => {
    try {
        // 动态导入echarts，避免模块找不到的问题
        const echarts = await import('echarts')

        nextTick(() => {
            if (orderChartRef.value) {
                orderChart = echarts.init(orderChartRef.value)
                updateOrderChart()
            }

            if (ganttChartRef.value) {
                ganttChart = echarts.init(ganttChartRef.value)
                updateGanttChart()
            }

            if (timelineChartRef.value) {
                timelineChart = echarts.init(timelineChartRef.value)
                updateTimelineChart()
            }

            if (efficiencyChartRef.value) {
                efficiencyChart = echarts.init(efficiencyChartRef.value)
                updateEfficiencyChart()
            }
        })
    } catch (error) {
        console.warn('ECharts模块未安装，图表功能将不可用。请运行: npm install echarts')
        ElMessage.warning('图表功能需要安装ECharts依赖，请先安装: npm install echarts')
    }
}

// 生命周期
onMounted(async () => {
    await initCharts()
    await loadDashboardData() // 初始化时加载数据
    startAutoRefresh()
    startRealtimeMonitoring()
})

onUnmounted(() => {
    stopAutoRefresh()
    stopRealtimeMonitoring()

    // 销毁图表实例
    if (orderChart) orderChart.dispose()
    if (ganttChart) ganttChart.dispose()
    if (timelineChart) timelineChart.dispose()
    if (efficiencyChart) efficiencyChart.dispose()
})
</script>

<style scoped>
/* ==================== 古风主容器样式 ==================== */
.ancient-dashboard-container {
    position: relative;
    padding: 20px;
    background: linear-gradient(135deg,
            #1a1a2e 0%,
            #16213e 25%,
            #0f3460 50%,
            #533483 75%,
            #7209b7 100%);
    min-height: 100vh;
    font-family: 'Microsoft YaHei', 'SimSun', serif;
    overflow-x: hidden;
}

/* ==================== 古风背景 ==================== */
.ancient-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
    pointer-events: none;
}

/* 山水背景 */
.mountain-landscape {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 60%;
}

.mountain-range {
    position: absolute;
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg,
            transparent 0%,
            rgba(139, 69, 19, 0.3) 30%,
            rgba(160, 82, 45, 0.4) 60%,
            rgba(101, 67, 33, 0.5) 100%);
    clip-path: polygon(0% 100%, 0% 60%, 20% 40%, 40% 50%, 60% 30%, 80% 45%, 100% 35%, 100% 100%);
    animation: ancientMountainGlow 8s ease-in-out infinite;
}

.mountain-peaks {
    position: absolute;
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg,
            transparent 0%,
            rgba(255, 215, 0, 0.2) 20%,
            rgba(255, 140, 0, 0.3) 40%,
            rgba(255, 69, 0, 0.2) 60%,
            transparent 100%);
    clip-path: polygon(0% 100%, 0% 50%, 15% 35%, 35% 45%, 55% 25%, 75% 40%, 100% 30%, 100% 100%);
    animation: ancientPeakGlow 6s ease-in-out infinite;
}

.mountain-shadow {
    position: absolute;
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg,
            transparent 0%,
            rgba(0, 0, 0, 0.2) 40%,
            rgba(0, 0, 0, 0.4) 100%);
    clip-path: polygon(0% 100%, 0% 70%, 20% 50%, 40% 60%, 60% 40%, 80% 55%, 100% 45%, 100% 100%);
}

.waterfall {
    position: absolute;
    right: 15%;
    top: 20%;
    width: 3px;
    height: 30%;
    background: linear-gradient(180deg,
            rgba(255, 255, 255, 0.6) 0%,
            rgba(200, 200, 255, 0.4) 50%,
            transparent 100%);
    border-radius: 2px;
    animation: ancientWaterfall 3s ease-in-out infinite;
}

/* 云雾效果 */
.clouds {
    position: absolute;
    width: 100%;
    height: 100%;
}

.cloud {
    position: absolute;
    background: radial-gradient(ellipse, rgba(255, 255, 255, 0.3), transparent);
    border-radius: 50%;
    animation: ancientCloudFloat linear infinite;
}

/* 古风粒子 */
.ancient-particles {
    position: absolute;
    width: 100%;
    height: 100%;
}

.particle {
    position: absolute;
    background: radial-gradient(circle, rgba(255, 215, 0, 0.8) 1px, transparent 1px);
    border-radius: 50%;
    animation: ancientParticleFloat linear infinite;
}

/* ==================== 古风页面标题 ==================== */
.ancient-page-header {
    position: relative;
    z-index: 10;
    text-align: center;
    margin-bottom: 30px;
    padding: 30px 20px;
    background: linear-gradient(135deg,
            rgba(139, 69, 19, 0.9) 0%,
            rgba(160, 82, 45, 0.95) 50%,
            rgba(101, 67, 33, 0.9) 100%);
    backdrop-filter: blur(15px);
    border: 3px solid rgba(255, 215, 0, 0.4);
    border-radius: 20px;
    box-shadow:
        0 25px 50px rgba(0, 0, 0, 0.6),
        inset 0 2px 0 rgba(255, 255, 255, 0.1);
}

.ancient-header-decoration {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    gap: 20px;
}

.decoration-left,
.decoration-right {
    width: 80px;
    height: 2px;
    background: linear-gradient(90deg, transparent, #ffd700, transparent);
    position: relative;
}

.decoration-left::before,
.decoration-right::before {
    content: '';
    position: absolute;
    top: -3px;
    width: 8px;
    height: 8px;
    background: #ffd700;
    border-radius: 50%;
    box-shadow: 0 0 10px rgba(255, 215, 0, 0.6);
}

.decoration-left::before {
    left: 0;
}

.decoration-right::before {
    right: 0;
}

.decoration-center {
    position: relative;
}

.ancient-logo {
    width: 60px;
    height: 60px;
    position: relative;
}

.logo-symbol {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 2rem;
    transform: translate(-50%, -50%);
    text-shadow: 0 0 15px rgba(255, 255, 255, 0.8);
}

.logo-circle {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 50px;
    height: 50px;
    border: 2px solid rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    transform: translate(-50%, -50%);
}

.ancient-page-title {
    color: #ffd700;
    font-size: 2rem;
    font-weight: bold;
    margin: 0 0 20px 0;
    text-shadow: 0 0 15px rgba(255, 215, 0, 0.6);
    font-family: 'Microsoft YaHei', serif;
}

.ancient-header-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
}

.ancient-action-btn {
    background: linear-gradient(135deg, #ffd700, #ff8c00);
    border: none;
    border-radius: 10px;
    color: #000000;
    font-weight: bold;
    padding: 10px 20px;
    box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
    transition: all 0.3s ease;
}

.ancient-action-btn:hover {
    background: linear-gradient(135deg, #ff8c00, #ffd700);
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(255, 215, 0, 0.5);
}

/* ==================== 古风统计卡片 ==================== */
.ancient-stats-grid {
    position: relative;
    z-index: 10;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 25px;
    margin-bottom: 30px;
}

.ancient-stat-card {
    position: relative;
    display: flex;
    align-items: center;
    padding: 25px;
    background: linear-gradient(135deg,
            rgba(255, 255, 255, 0.95) 0%,
            rgba(248, 248, 255, 0.9) 100%);
    border: 2px solid rgba(255, 215, 0, 0.3);
    border-radius: 15px;
    box-shadow:
        0 15px 35px rgba(0, 0, 0, 0.3),
        inset 0 2px 0 rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;
    overflow: hidden;
}

.ancient-stat-card:hover {
    transform: translateY(-5px);
    box-shadow:
        0 20px 45px rgba(0, 0, 0, 0.4),
        inset 0 2px 0 rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 215, 0, 0.5);
}

.ancient-card-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
}

.card-corner {
    position: absolute;
    width: 20px;
    height: 20px;
    border: 2px solid rgba(255, 215, 0, 0.6);
}

.card-corner.top-left {
    top: 10px;
    left: 10px;
    border-right: none;
    border-bottom: none;
}

.card-corner.top-right {
    top: 10px;
    right: 10px;
    border-left: none;
    border-bottom: none;
}

.card-corner.bottom-left {
    bottom: 10px;
    left: 10px;
    border-right: none;
    border-top: none;
}

.card-corner.bottom-right {
    bottom: 10px;
    right: 10px;
    border-left: none;
    border-top: none;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
}

.stat-icon-primary {
    background: linear-gradient(135deg, #409eff, #66b3ff);
    color: white;
}

.stat-icon-success {
    background: linear-gradient(135deg, #67c23a, #85ce61);
    color: white;
}

.stat-icon-warning {
    background: linear-gradient(135deg, #e6a23c, #ebb563);
    color: white;
}

.stat-icon-info {
    background: linear-gradient(135deg, #909399, #a6a9ad);
    color: white;
}

.stat-icon .el-icon {
    font-size: 24px;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #333;
    margin-bottom: 4px;
}

.stat-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
}

.stat-trend {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    font-weight: 500;
}

.trend-up {
    color: #67c23a;
}

.trend-down {
    color: #f56c6c;
}

.charts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 24px;
}

.chart-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
}

.chart-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.chart-content {
    padding: 20px;
}

.chart-container {
    width: 100%;
    height: 300px;
}

.monitor-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 24px;
}

.monitor-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.monitor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
}

.monitor-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.auto-refresh-label {
    margin-left: 8px;
    font-size: 12px;
    color: #666;
}

.monitor-content {
    padding: 20px;
    max-height: 400px;
    overflow-y: auto;
}

/* 生产进度监控样式 */
.production-progress-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.production-item {
    padding: 20px;
    border: 1px solid #e8f4fd;
    border-radius: 12px;
    background: linear-gradient(135deg, #f8fbff 0%, #f0f9ff 100%);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
    transition: all 0.3s ease;
}

.production-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(24, 144, 255, 0.15);
}

.production-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.production-name {
    font-size: 16px;
    font-weight: 600;
    color: #1890ff;
}

.production-status {
    font-size: 12px;
    padding: 6px 12px;
    border-radius: 20px;
    font-weight: 500;
}

.status-running {
    background: #e6f7ff;
    color: #1890ff;
    border: 1px solid #91d5ff;
}

.status-stopped {
    background: #fff2f0;
    color: #ff4d4f;
    border: 1px solid #ffb3b3;
}

.status-low-speed {
    background: #fff7e6;
    color: #faad14;
    border: 1px solid #ffd591;
}

.production-progress-bar {
    margin-bottom: 16px;
}

.progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
}

.progress-percentage {
    font-size: 18px;
    font-weight: 700;
    color: #1890ff;
}

.progress-label {
    font-size: 12px;
    color: #8c8c8c;
}

.production-details {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 16px;
}

.detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 6px;
}

.detail-label {
    font-size: 12px;
    color: #666;
}

.detail-value {
    font-size: 13px;
    font-weight: 600;
    color: #333;
}

.production-lines {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.line-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
}

.line-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.line-name {
    color: #666;
    font-weight: 500;
}

/* 统计卡片单位样式 */
.stat-unit {
    font-size: 14px;
    color: #8c8c8c;
    margin-left: 4px;
    font-weight: 400;
}

.material-alerts {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.alert-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border-radius: 8px;
    border-left: 4px solid;
}

.alert-warning {
    background: #fff7e6;
    border-left-color: #faad14;
}

.alert-danger {
    background: #fff2f0;
    border-left-color: #ff4d4f;
}

.alert-info {
    background: #f6ffed;
    border-left-color: #52c41a;
}

.alert-icon {
    margin-right: 12px;
    font-size: 20px;
}

.alert-warning .alert-icon {
    color: #faad14;
}

.alert-danger .alert-icon {
    color: #ff4d4f;
}

.alert-info .alert-icon {
    color: #52c41a;
}

.alert-content {
    flex: 1;
}

.alert-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.alert-material {
    font-size: 14px;
    font-weight: 600;
    color: #333;
}

.alert-status {
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 12px;
    font-weight: 500;
}

.status-danger {
    background: #ff4d4f;
    color: white;
}

.status-warning {
    background: #faad14;
    color: white;
}

.status-info {
    background: #52c41a;
    color: white;
}

.alert-details {
    margin-bottom: 8px;
}

.alert-desc {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    font-size: 12px;
}

.alert-desc .label {
    color: #666;
    font-weight: 500;
}

.alert-desc .value {
    color: #333;
    font-weight: 600;
}

.alert-time {
    font-size: 11px;
    color: #999;
}

.alert-action {
    margin-left: 12px;
}

/* 工单状态监控样式 */
.order-monitor-section {
    margin-bottom: 24px;
}

.order-monitor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 4px;
}

.order-monitor-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.order-controls {
    display: flex;
    gap: 8px;
}

.order-status-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
}

.order-status-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    border-left: 4px solid;
}

.order-status-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.status-info {
    border-left-color: #1890ff;
    background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
}

.status-warning {
    border-left-color: #faad14;
    background: linear-gradient(135deg, #fff7e6 0%, #fff2e6 100%);
}

.status-success {
    border-left-color: #52c41a;
    background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
}

.status-danger {
    border-left-color: #ff4d4f;
    background: linear-gradient(135deg, #fff2f0 0%, #ffe6e6 100%);
}

.status-icon {
    display: flex;
    justify-content: center;
    margin-bottom: 12px;
    font-size: 24px;
}

.status-info .status-icon {
    color: #1890ff;
}

.status-warning .status-icon {
    color: #faad14;
}

.status-success .status-icon {
    color: #52c41a;
}

.status-danger .status-icon {
    color: #ff4d4f;
}

.status-content {
    text-align: center;
}

.status-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
}

.status-count {
    font-size: 24px;
    font-weight: 700;
    color: #333;
    margin-bottom: 4px;
}

.status-percentage {
    font-size: 12px;
    color: #666;
    font-weight: 500;
}

.efficiency-grid {
    margin-bottom: 24px;
}

.efficiency-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.efficiency-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
}

.efficiency-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.efficiency-content {
    padding: 20px;
}

.efficiency-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.efficiency-stat {
    text-align: center;
    padding: 16px;
    background: #fafafa;
    border-radius: 8px;
}

.stat-label {
    font-size: 12px;
    color: #666;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 24px;
    font-weight: 700;
    color: #333;
}

.efficiency-chart {
    width: 100%;
    height: 300px;
}

.realtime-data {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.realtime-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
}

.realtime-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.realtime-controls {
    display: flex;
    align-items: center;
    gap: 12px;
}

.realtime-label {
    font-size: 12px;
    color: #666;
}

.realtime-content {
    padding: 20px;
    max-height: 300px;
    overflow-y: auto;
}

.data-stream {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.stream-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
}

.event-success {
    background: #f6ffed;
    border-left: 3px solid #52c41a;
}

.event-warning {
    background: #fff7e6;
    border-left: 3px solid #faad14;
}

.event-info {
    background: #e6f7ff;
    border-left: 3px solid #1890ff;
}

.stream-time {
    color: #999;
    margin-right: 12px;
    min-width: 60px;
}

.stream-content {
    flex: 1;
    color: #333;
}

.stream-source {
    color: #666;
    font-size: 11px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .charts-grid {
        grid-template-columns: 1fr;
    }

    .monitor-grid {
        grid-template-columns: 1fr;
    }

    .efficiency-stats {
        grid-template-columns: repeat(2, 1fr);
    }
}

/* ==================== 古风动画定义 ==================== */
@keyframes ancientMountainGlow {

    0%,
    100% {
        opacity: 0.3;
    }

    50% {
        opacity: 0.6;
    }
}

@keyframes ancientPeakGlow {

    0%,
    100% {
        opacity: 0.2;
    }

    50% {
        opacity: 0.5;
    }
}

@keyframes ancientWaterfall {

    0%,
    100% {
        opacity: 0.6;
        transform: translateY(0);
    }

    50% {
        opacity: 1;
        transform: translateY(3px);
    }
}

@keyframes ancientCloudFloat {
    0% {
        transform: translateX(-100px);
        opacity: 0;
    }

    10% {
        opacity: 0.3;
    }

    90% {
        opacity: 0.3;
    }

    100% {
        transform: translateX(calc(100vw + 100px));
        opacity: 0;
    }
}

@keyframes ancientParticleFloat {
    0% {
        transform: translateY(100vh) rotate(0deg);
        opacity: 0;
    }

    10% {
        opacity: 0.8;
    }

    90% {
        opacity: 0.8;
    }

    100% {
        transform: translateY(-100px) rotate(360deg);
        opacity: 0;
    }
}

@media (max-width: 768px) {
    .ancient-stats-grid {
        grid-template-columns: 1fr;
    }

    .ancient-page-header {
        padding: 20px 15px;
    }

    .ancient-page-title {
        font-size: 1.5rem;
    }

    .ancient-header-actions {
        flex-direction: column;
        gap: 10px;
    }

    .ancient-action-btn {
        width: 100%;
    }
}
</style>
